#include "core_pch.h"
#include "Utility.h"
#include "OgreErrorDialog.h"

const size_t Mem_Alloc_Aligned = 4;

void* coreRealloc(void* ptr, u32_t oldSize, u32_t newSize)
{
	void* rstPtr = null_ptr;
	if( newSize)
	{
		rstPtr = OGRE_MALLOC_ALIGN( newSize, Ogre::MEMCATEGORY_GENERAL, Mem_Alloc_Aligned);
		if( oldSize)
		{
			u32_t copySize = Min( oldSize, newSize);
			coreMemcpy( rstPtr, ptr, copySize);
		}
	}
		
	if( oldSize)
	{
		OGRE_FREE_ALIGN( ptr, Ogre::MEMCATEGORY_GENERAL, Mem_Alloc_Aligned);
	}

	return rstPtr;
}


void* coreAlloc( u32_t size)
{
	void* rstPtr = OGRE_MALLOC_ALIGN( size, Ogre::MEMCATEGORY_GENERAL, Mem_Alloc_Aligned);
	_check( rstPtr);
	return  rstPtr;
}

void coreFree( void* data)
{
	if( data)
	{
		OGRE_FREE_ALIGN( data, Ogre::MEMCATEGORY_GENERAL, Mem_Alloc_Aligned);
	}

}

char* coreStrcpy(char* pcDest, s32_t stDestSize, const char* pcSrc)
{
    _check(stDestSize != 0);

    s32_t stSrcLen = strlen(pcSrc);
    _check(stDestSize > stSrcLen); // > because need null character

    s32_t stWrite;
    
    if (stDestSize <= stSrcLen) // stDestSize < stSrcLen + 1
        stWrite = stDestSize;
    else 
        stWrite = stSrcLen + 1;

    char *pcResult = strncpy(pcDest, pcSrc, stWrite);
    pcResult[stDestSize - 1] = '\0';
    return pcResult;
}
char* coreStrncpy( char* pcDest, s32_t stDestSize, const char* pcSrc, s32_t stCount)
{
   _check( pcDest != 0 && stDestSize != 0);
   _check( stCount < stDestSize || stCount == null_index);

    if (stCount >= stDestSize)
    {
		if (stCount != null_index)
        {
            pcDest[0] = '\0';
            return pcDest;
        }
        else
        {
            stCount = stDestSize - 1;
        }
    }

    char* pcResult = strncpy(pcDest, pcSrc, stCount);
    pcResult[stCount] = '\0';

    return pcResult;
}



void coreErrDialog( const as_char_t* expr, const as_char_t* fileName, s32_t lineNum)
{
	Ogre::ErrorDialog diag;
	Ogre::String viewText = "Error: ";
	viewText += expr;
	viewText += " File: ";
	viewText += fileName;
	viewText += " Line: ";
	viewText += Ogre::StringConverter::toString( lineNum);
	viewText += ".";
	diag.display( viewText);
}
